<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width"/>
    <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
    <title>Hello APP</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css"/>
    <style>
        body {
            font-size: 14px;
        }

        div {
            text-align: center;
        }

        #connect-btn {
            background-color: #467cff;
            border-radius: 50%;
            width: 100px;
            line-height: 100px;
            display: inline-block;
            font-size: 18px;
            color: white;
            margin-top: 220px;
            transition: all 0.5s 0s;
        }

        #panel {
            text-align: unset;
            width: 90%;
            transition: all 1s 0s;
            padding: 5px 5%;
            margin: 0 auto;
        }

        #panel p {
            text-align: center;
        }

        #panel input {
            border: 1px solid #467cff;
            height: 30px;
            padding: 4px 8px;
            width: 70%;
        }

        #panel button {
            border: 1px solid #467cff;
            height: 40px;
            padding: 13px;
        }

        #panel p {
            margin-top: .5pc;
            margin-bottom: 1pc;
        }

        #color input {
            width: 25%;
            text-align: center;
        }

        #set button {
            width: 32%;

        }

        input, button {
            outline: none;
        }
    </style>
</head>
<body>
<div>
    <a id="connect-btn" onclick="device_search()">搜索设备</a>
</div>

<div id="panel">
    <h3>氛围灯最低亮度 <span style="font-weight: 400;font-size: 12px">范围 0-200，默认 0</span></h3>
    <p>
        <input id="MLS" type="number" placeholder="值越大，亮度越高">
        <button onclick="send_cmd(1)">设置</button>
    </p>

    <h3>车门&传感器距离 <span style="font-weight: 400;font-size: 12px">范围 50-250mm，默认 100</span></h3>
    <p>
        <input id="DOT" type="number" placeholder="根据激光传感器与车门的距离调节">
        <button onclick="send_cmd(2)">设置</button>
    </p>

    <h3>车辆侧倾阈值 <span style="font-weight: 400;font-size: 12px">范围 0-999，默认 0</span></h3>
    <p>
        <input id="ART" type="number" placeholder="值越小，车辆侧倾&颠簸提醒越灵敏">
        <button onclick="send_cmd(3)">设置</button>
    </p>

    <h3>氛围灯颜色 <span style="font-weight: 400;font-size: 12px">范围 红0-255 绿0-255 蓝0-255</span></h3>
    <p id="color">
        <input id="RED" type="number" onkeyup="update_color_panel()" placeholder="红色值">
        <input id="GREEN" type="number" onkeyup="update_color_panel()" placeholder="绿色值">
        <input id="BLUE" type="number" onkeyup="update_color_panel()" placeholder="蓝色值">
    </p>
    <p id="set">
        <button onclick="send_cmd(4)">开门颜色</button>
        <button onclick="send_cmd(5)">点亮颜色</button>
        <button onclick="send_cmd(6)">关门颜色</button>
    </p>
</div>
<div id="arccolor"></div>

</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript">
    var bluetoothSerial;
    var arcColorPicker;

    var has_device = false;
    var bluetooth_ok = false;

    var color_ok = false;

    var connect_btn = document.getElementById("connect-btn");
    var panel = document.getElementById("panel");

    var arccolor = document.getElementById('arccolor');

    var MLS = document.getElementById("MLS");
    var DOT = document.getElementById("DOT");
    var ART = document.getElementById("ART");
    var RED = document.getElementById("RED");
    var GREEN = document.getElementById("GREEN");
    var BLUE = document.getElementById("BLUE");

    apiready = function () {
        bluetoothSerial = api.require("cxgBluetoothSerial");
        arcColorPicker = api.require('arcColorPicker');

        arcColorPicker.open({
            y: 620,
            r: 90,
            style: {
                ringWidth: 32
            },
            gradients: ['#000000', '#FFFFFF', '#FF0000', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#FF00FF', '#FF0000'],
            fixedOn: api.frameName,
            fixed: false
        }, function (ret, err) {
            if (ret) {
                if (color_ok) {
                    console.log(ret.color);
                    RED.value = color2val(ret.color, 'r');
                    GREEN.value = color2val(ret.color, 'g');
                    BLUE.value = color2val(ret.color, 'b');
                } else {
                    color_ok = true;
                }
            }
        });

        arcColorPicker.hide();

        initial();
    };

    function arc_color(show) {
        if (show) {
            connect_btn.style.marginTop = '15px';
            connect_btn.style.width = '100px';
            connect_btn.style.lineHeight = '100px';
            connect_btn.style.fontSize = '18px';

            panel.style.display = 'block';

            arccolor.style.height = '180px';
        } else {
            connect_btn.style.marginTop = '220px';
            connect_btn.style.width = '140px';
            connect_btn.style.lineHeight = '140px';
            connect_btn.style.fontSize = '25px';

            panel.style.display = 'none';

            arccolor.style.height = '0';
        }
    }

    function update_color_panel() {
        var has_error = 3;
        var msg = '';

        var re = /^[0-9]+[0-9]*$/;

        if (re.test(RED.value) && RED.value >= 0 && RED.value <= 255) {
            has_error--;
        } else {
            msg += '红色 ';
        }

        if (re.test(GREEN.value) && GREEN.value >= 0 && GREEN.value <= 255) {
            has_error--;
        } else {
            msg += '绿色 ';
        }

        if (re.test(BLUE.value) && BLUE.value >= 0 && BLUE.value <= 255) {
            has_error--;
        } else {
            msg += '蓝色 ';
        }

        if (msg) {
            api.toast({
                msg: msg + '设置错误',
                duration: 500,
                location: 'bottom'
            });
        }

        if (has_error === 0) {
            var red_hex = parseInt(RED.value) > 15 ? parseInt(RED.value).toString(16) : '0' + parseInt(RED.value).toString(16);
            var green_hex = parseInt(GREEN.value) > 15 ? parseInt(GREEN.value).toString(16) : '0' + parseInt(GREEN.value).toString(16);
            var blue_hex = parseInt(BLUE.value) > 15 ? parseInt(BLUE.value).toString(16) : '0' + parseInt(BLUE.value).toString(16);

            console.log('#' + red_hex + green_hex + blue_hex)
            arcColorPicker.setColor({
                color: '#' + red_hex + green_hex + blue_hex
            });
        }
    }

    function color2val(color, val) {
        if (color.length === 7) {
            if (val === 'r') {
                color = color.substr(1, 2);
            } else if (val === 'g') {
                color = color.substr(3, 2);
            } else if (val === 'b') {
                color = color.substr(5, 2);
            } else {
                return false;
            }

            var str_ascii1 = color.substr(0, 1).charCodeAt();
            var str_ascii2 = color.substr(1, 1).charCodeAt();

            color = (str_ascii1 - (str_ascii1 >= 65 ? 87 : 48)) * 16;
            color += (str_ascii2 - (str_ascii2 >= 65 ? 87 : 48));
        } else {
            return false;
        }

        return color;
    }

    function initial() {
        arc_color(0);

        bluetooth_open();
    }

    function send_cmd(opt) {
        var cmd = '';
        var re = /^[0-9]+[0-9]*$/;

        switch (opt) {
            case 1: {
                if (re.test(MLS.value)) {
                    if (MLS.value >= 0 && MLS.value <= 200) {
                        cmd = 'MLS' + MLS.value + '#';
                    } else {
                        cmd = false;
                    }
                } else {
                    cmd = false;
                }
                break;
            }
            case 2: {
                if (re.test(DOT.value)) {
                    if (DOT.value >= 50 && DOT.value <= 250) {
                        cmd = 'DOT' + DOT.value + '#';
                    } else {
                        cmd = false;
                    }
                } else {
                    cmd = false;
                }
                break;
            }
            case 3: {
                if (re.test(ART.value)) {
                    if (ART.value >= 0 && ART.value <= 999) {
                        cmd = 'ART' + ART.value + '#';
                    } else {
                        cmd = false;
                    }
                } else {
                    cmd = false;
                }
                break;
            }
            case 4: {
                if (re.test(RED.value) && re.test(GREEN.value) && re.test(BLUE.value)) {
                    if (RED.value >= 0 && RED.value <= 255 && GREEN.value >= 0 && GREEN.value <= 255 && BLUE.value >= 0 && BLUE.value <= 255) {
                        cmd = 'SCS' + RED.value + ',' + GREEN.value + ',' + BLUE.value + '#';
                    } else {
                        cmd = false;
                    }
                } else {
                    cmd = false;
                }
                break;
            }
            case 5: {
                if (re.test(RED.value) && re.test(GREEN.value) && re.test(BLUE.value)) {
                    if (RED.value >= 0 && RED.value <= 255 && GREEN.value >= 0 && GREEN.value <= 255 && BLUE.value >= 0 && BLUE.value <= 255) {
                        cmd = 'LCS' + RED.value + ',' + GREEN.value + ',' + BLUE.value + '#';
                    } else {
                        cmd = false;
                    }
                } else {
                    cmd = false;
                }
                break;
            }
            case 6: {
                if (re.test(RED.value) && re.test(GREEN.value) && re.test(BLUE.value)) {
                    if (RED.value >= 0 && RED.value <= 255 && GREEN.value >= 0 && GREEN.value <= 255 && BLUE.value >= 0 && BLUE.value <= 255) {
                        cmd = 'ECS' + RED.value + ',' + GREEN.value + ',' + BLUE.value + '#';
                    } else {
                        cmd = false;
                    }
                } else {
                    cmd = false;
                }
                break;
            }
            default: {
                cmd = false;
                break;
            }
        }
        if (cmd) {
            console.log(cmd);

            bluetoothSerial.sendData({data: cmd},
                function (ret, err) {
                    if (!err) {
                        didi();
                    } else {
                        alert("code: " + err.code + " msg: " + err.msg);
                    }
                }
            );
        } else {
            alert("命令无效");
        }
    }

    function device_search() {
        if (!bluetooth_ok) {
            alert("请打开手机蓝牙后重启本软件！")
        } else {
            if (!has_device) {
                didi();
                connect_btn.innerText = "正在搜索";

                api.showProgress({
                    title: '搜索设备中...',
                    text: '先喝杯茶...',
                    modal: true
                });
                bluetooth_scan();
            } else {
                connect_btn.innerText = "正在断开";
                bluetoothSerial.disconnect({}, function (ret, err) {
                    didi();
                    if (!err) {
                        panel.style.marginLeft = "-100%";
                        connect_btn.innerText = "搜索设备";
                        has_device = false;
                        arcColorPicker.hide();
                        arc_color(0);
                    } else {
                        connect_btn.innerText = "断开连接";
                        alert("code: " + err.code + " msg: " + err.msg);
                    }
                    api.hideProgress();
                });
            }

        }
    }

    function bluetooth_open() {
        bluetoothSerial.isEnabledBluetooth({}, function (ret, err) {
            if (!err) {
                if (ret.state) {
                    bluetooth_ok = true;
                }
            }
        });
    }

    function bluetooth_scan() {
        bluetoothSerial.scan({}, function (ret, err) {
            if (err.code === 1) {
                alert(err.msg);
            }
            if (!err) {
                if (ret.data === "ACTION_DISCOVERY_FINISHED") {
                    if (!has_device) {
                        connect_btn.innerText = "搜索设备";
                        alert("未搜索到设备");
                    }
                    api.hideProgress();
                } else {
                    console.log(JSON.stringify(ret.data));
                    if (ret.data.name === "JDY-31-SPP" && !has_device) {
                        didi();
                        bluetoothSerial.stopScan({}, function (ret, err) {
                        });

                        api.showProgress({
                            title: '连接设备中...',
                            text: '先喝杯茶...',
                            modal: true
                        });

                        has_device = true;
                        connect_btn.innerText = "正在连接";

                        bluetoothSerial.connect({
                                address: ret.data.address
                            },
                            function (ret, err) {
                                didi();
                                if (!err) {
                                    connect_btn.innerText = "断开连接";
                                    panel.style.marginLeft = "0";

                                    setTimeout(function () {
                                        arcColorPicker.show();
                                    }, 500);
                                    arc_color(1);
                                } else {
                                    has_device = false;
                                    alert("连接失败，请重试！");
                                    connect_btn.innerText = "搜索设备";

                                    arcColorPicker.hide();
                                    arc_color(0);
                                }
                                api.hideProgress();
                            }
                        );
                    }
                }
            } else {
                if (err.code === 0) {
                    bluetooth_ok = false;
                    panel.style.marginLeft = "-100%";
                    alert("请打开手机蓝牙后重启本软件！")
                }
            }
        });
    }

    function didi() {
        api.startPlay({
            path: 'widget://res/di.mp3'
        }, function (ret, err) {
        });
    }
</script>
</html>
